package org.shuma.oss.mng.impl;

import com.alipay.sofa.runtime.api.annotation.SofaService;
import com.alipay.sofa.runtime.api.annotation.SofaServiceBinding;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import lombok.extern.slf4j.Slf4j;
import org.shuma.oss.facade.UploadFile;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Objects;

/**
 * @author zhao haitao
 * @date 2024/06/17 12:51 AM
 */
@Service
@SofaService(interfaceType = UploadFile.class, uniqueId = "${service.unique.id}", bindings = {@SofaServiceBinding(bindingType = "bolt")})
@Slf4j
public class uploadFileImpl implements UploadFile {
    @Value("${qiniu.accessKey}")
    // 设置好账号的ACCESS_KEY和SECRET_KEY
    private String ACCESS_KEY;
    @Value("${qiniu.secretKey}")
    private String SECRET_KEY;
    // 要上传的空间
    @Value("${qiniu.bucketName}")
    private String bucketName;
    @Value("${qiniu.domain}")
    private String QINIU_IMAGE_DOMAIN;

    @Override
    public String uploadByInputStream(MultipartFile file, String fileName, String filePath) {
        // 获取文件名的最后一个点号位置
        int dotPos = Objects.requireNonNull(file.getOriginalFilename()).lastIndexOf(".");
        // 如果点号位置小于0，则返回null
        if (dotPos < 0 || file.isEmpty()) {
            return null;
        }
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.autoRegion());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
        // ...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        try {
            Response res = uploadManager.put(file.getInputStream(), filePath + fileName, auth.uploadToken(bucketName), null, null);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(res.bodyString(), DefaultPutRet.class);
            // 打印返回的信息
            if (res.isOK() && res.isJson()) {
                // 返回这张存储照片的地址
                return QINIU_IMAGE_DOMAIN + "/" + putRet.key;
            } else {
                log.error("七牛异常: {}", res.bodyString());
                return "";
            }
        } catch (QiniuException e) {
            // 请求失败时打印的异常的信息
            log.error("七牛异常:{}", e.getMessage());
            return "";
        } catch (IOException e) {
            log.error("file.getBytes()异常:{}", e.getMessage());
            throw new RuntimeException(e);
        }
    }

}
